//
//  ReadListViewController.m
//  leisure
//
//  Created by xalo on 16/4/19.
//  Copyright © 2016年 Mr.wangYongxu. All rights reserved.
//

#import "ReadListViewController.h"
#import "ReadModel.h"
#import "ReadListModel.h"
#import "ReadListTableViewCell.h"
#import "ReadDetailViewController.h"



#define kReadListURL @"http://api2.pianke.me/read/columns_detail"

typedef enum{
    ReadListAddTime,
    ReadListHotTime,
}DataType;

@interface ReadListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *addtimeTableView;//最新列表
@property (weak, nonatomic) IBOutlet UITableView *hotTableView;//热门列表
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentController;//分段视图控制器
@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;//滚动视图
@property (strong, nonatomic)NSMutableArray* addTimeDataSourceArr;//最新数据数组
@property (strong, nonatomic)NSMutableDictionary* parameters;//请求参数
@property (strong, nonatomic)NSMutableArray* hotDataSourceArr;//最热数据数组
@property (assign, nonatomic)DataType datatype;//请求的数据类型
@property (assign, nonatomic)NSInteger hotStartInteger;
@property (assign, nonatomic)NSInteger addTimeStartInteger;
@end

@implementation ReadListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.datatype = ReadListAddTime;
    [self _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
    [self.addtimeTableView registerNib:[UINib nibWithNibName:@"ReadListTableViewCell" bundle:nil] forCellReuseIdentifier:@"ReadListTableViewCell"];
    [self.hotTableView registerNib:[UINib nibWithNibName:@"ReadListTableViewCell" bundle:nil] forCellReuseIdentifier:@"ReadListTableViewCell"];
    [self setMJFreshUpDown];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//最热数据数组加载
-(NSMutableArray *)hotDataSourceArr{
    
    if (!_hotDataSourceArr) {
        _hotDataSourceArr = [NSMutableArray array];
    }
    return _hotDataSourceArr;
}

//最新数据数组懒加载
-(NSMutableArray *)addTimeDataSourceArr{
    
    if (!_addTimeDataSourceArr) {
        _addTimeDataSourceArr = [NSMutableArray array];
    }
    return _addTimeDataSourceArr;
}
//参数懒加载
-(NSMutableDictionary *)parameters{
    
    if (!_parameters) {
        _parameters = [NSMutableDictionary dictionaryWithDictionary:@{@"sort":@"addtime",@"limit":@10,@"typeid":@(self.readModel.type),@"start":@0}];
    }
    return _parameters;
}

- (IBAction)clickSegment:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0://最新
        {
            [self.scrollerView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
            break;
        case 1://最热
        {
            [self.scrollerView setContentOffset:CGPointMake(kViewWidth, 0) animated:YES];
        }
            break;
        default:
            break;
    }
}
#pragma mark -  <UIScrollViewDelegate>
//滑动加载
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView == self.scrollerView) {
        if (scrollView.contentOffset.x == 0) {
            self.segmentController.selectedSegmentIndex = 0;
            self.datatype = ReadListAddTime;
            [self.parameters setValue:@"addtime" forKey:@"sort"];
            if (self.addTimeDataSourceArr.count == 0) {
                [self _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
            }
        }else if(scrollView.contentOffset.x == kViewWidth){
            self.segmentController.selectedSegmentIndex = 1;
            self.datatype = ReadListHotTime;
            [self.parameters setValue:@"hot" forKey:@"sort"];
            if (self.hotDataSourceArr.count == 0) {
                [self _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
            }
            
        }
    }

}


#pragma mark - <UITableViewDelegate>
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ReadListModel* model = nil;
    if (tableView == self.hotTableView) {
        model = self.hotDataSourceArr[indexPath.row];
    }
    if (tableView == self.addtimeTableView) {
        model = self.addTimeDataSourceArr[indexPath.row];
    }
    if (model) {
        ReadDetailViewController* detail = [[ReadDetailViewController alloc] init];
        detail.model = model;
        [self.navigationController pushViewController:detail animated:YES];
    }
    
}
#pragma mark - <UITableViewDataSource>
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ReadListTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ReadListTableViewCell" forIndexPath:indexPath];
    if (tableView == self.addtimeTableView) {
        [cell setCellWithReadListModel:self.addTimeDataSourceArr[indexPath.row]];
    }else if(tableView == self.hotTableView){
        [cell setCellWithReadListModel:self.hotDataSourceArr[indexPath.row]];
    }
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger count;
    if (tableView == self.addtimeTableView) {
        count = self.addTimeDataSourceArr.count;
        
    }else if(tableView == self.hotTableView){
        count = self.hotDataSourceArr.count;
    }
   return count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}
#pragma mark - AFNetworking
-(void)_fetchSourceDataWithURl:(NSString*)url parameter:(NSDictionary*)dictionary{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:dictionary progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary* datasourceDic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSArray* list = [[datasourceDic objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary* object in list) {
            ReadListModel* model = [[ReadListModel alloc] init];
            [model setValuesForKeysWithDictionary:object];
            if (self.datatype == ReadListAddTime) {
                [self.addTimeDataSourceArr addObject:model];
            }else{
                [self.hotDataSourceArr addObject:model];
            }
        }
        [self.addtimeTableView reloadData];
        [self.hotTableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.addtimeTableView.mj_header endRefreshing];
        [self.addtimeTableView.mj_footer endRefreshing];
        [self.addtimeTableView.mj_header endRefreshing];
        [self.addtimeTableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"0");
    }];
}

- (void)setMJFreshUpDown
{

    _hotStartInteger = [self.parameters[@"start"] intValue];
    _addTimeStartInteger = [self.parameters[@"start"] intValue];
    __weak ReadListViewController *weakSelf = self;

    //addtime
    //下拉刷新
    self.addtimeTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.parameters setValue:@"addtime" forKey:@"sort"];
        [weakSelf _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
    }];
    //上拉加载
    self.addtimeTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.addTimeStartInteger += 10;
        [weakSelf.parameters setValue:@(_addTimeStartInteger) forKey:@"start"];
        [weakSelf.parameters setValue:@"addtime" forKey:@"sort"];
        [weakSelf _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
    }];

    //hot
    //下拉刷新
    self.hotTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.parameters setValue:@"hot" forKey:@"sort"];
        [weakSelf _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
    }];
    //上拉加载

    self.hotTableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        weakSelf.hotStartInteger += 10;
        [weakSelf.parameters setValue:@(_hotStartInteger) forKey:@"start"];
        [weakSelf.parameters setValue:@"hot" forKey:@"sort"];
        [weakSelf _fetchSourceDataWithURl:kReadListURL parameter:self.parameters];
    }];
    //    self.hotTableView.mj_footer
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
